<?php

namespace App\Admin\Controllers;

use App\Models\Site;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class SiteController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '站点管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Site());
        $grid->model()->orderBy('order');
        $grid->column('prefix', 'prefix')->link(function ($model) {
            return url($model->prefix);
        });
        $grid->column('name', __('站点名称'));
        $grid->column('order', '排序')->editable();
        $grid->column('icon', 'icon')->image('/');
        $states = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];
        $grid->column('enabled', '启用')->switch($states);
        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));
        $grid->disableExport();
        $grid->disableFilter();
        $grid->disablePagination();
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
            $actions->disableDelete();
        });
        $grid->batchActions(function (Grid\Tools\BatchActions $actions) {
            $actions->disableDeleteAndHodeSelectAll();
        });
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Site());

        $form->text('name', __('站点名称'));
        $form->text('prefix', __('prefix'));
        $form->text('icon', __('icon'));
        $states = [
            'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
        ];
        $form->switch('enabled', '启用')->default(1)->states($states);
        $form->text('order', '排序');

        $form->saving(function (Form $form) {
            if ($form->icon && !file_exists(public_path($form->icon))) {
                return back()->withInput(request()->all())
                    ->withErrors([
                        'icon' => '该图片不存在此'
                    ]);
            }
        });
        $form->saved(function () {
            Site::forgetCache();
        });
        $form->deleted(function () {
            Site::forgetCache();
        });
        return $form;
    }
}
